﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Model;
using SDT.Model.Properties;
using SDT.Lib.Common;
using SDT.Lib.Paging;
using SDT.Lib.Helpers;
using System.IO;
namespace SDT.Admin.Controllers
{
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class UsefulController : Controller
    {
        /// <summary>
        /// Created by Vietlv
        /// Date 12/07/2011
        /// Description: Manage Useful - Class useful controler;
        /// </summary>
        /// <returns></returns>

        SDTDataContext eDataConttext = new SDTDataContext();

        #region GET: /Useful/Index
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null) page = 1;
                    string order = UserState.getUserStateFromRequest("Useful.orderColum", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("Useful.orderDirection", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("Useful.Keyword", "Keyword", "").ToString();
                    int pagesize = Convert.ToInt32(UserState.getUserStateFromRequest("Useful.PageSize", "PageSize", Settings.Default.PageSize));
                    var listUseful = eDataConttext.Usefuls
                        .Where(e => string.IsNullOrEmpty(keyword) ? true : (e.Title.ToLower().Contains(keyword.ToLower().Trim()) || e.Description.Contains(keyword.Trim())))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pagesize);
                    ViewData["order"] = order;
                    ViewData["orderDir"] = orderDir;
                    return View(new UsefulIndexViewmodel
                    {
                        Usefuls = listUseful,
                        Keyword = keyword,
                        ImageRootUrl =Settings.Default.SiteRootUrl+ Settings.Default.UsefulImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Useful/Details/5

        public ActionResult Details(int id)
        {
                var itemUseful = eDataConttext.Usefuls.Single(e => e.ID == id);
                return View(new UsefulEditViewmodel {
                    Useful = itemUseful,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.UsefulImagePreviewUrlPrefix
                });
        }
        #endregion

        #region GET: /Useful/Create

        public ActionResult Create()
        {
                return View();

        }
        #endregion

        #region POST: /Useful/Create

        [HttpPost]
        public ActionResult Create(Useful fromdata)
        {
                try
                {
                    UpdateModel(fromdata);
                    fromdata.AddDate = DateTime.Now;
                    fromdata.AddBy = UserManager.GetUserId();
                    eDataConttext.Usefuls.InsertOnSubmit(fromdata);
                    eDataConttext.SubmitChanges();

                    //Image upload
                    HttpPostedFileBase fileImage = Request.Files["UseImage"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        fromdata.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.UsefulImageRootPath), "" + fromdata.ID);
                    }
                    eDataConttext.SubmitChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception exp)
                {
                    ViewData[Messages.MessageInfo] = exp.Message;
                    return View();
                }
        }
        #endregion

        #region GET: /Useful/Delete/5

        public ActionResult Delete(int id)
        {
                try
                {
                    var item = eDataConttext.Usefuls.Single(e => e.ID == id);

                    return View(item);
                }
                catch (Exception exp)
                {
                    ViewData[Messages.MessageInfo] = exp.Message;
                    return View();
                }
        }
        #endregion

        #region POST: /Useful/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
                try
                {
                    var item = eDataConttext.Usefuls.Single(e => e.ID == id);
                    if (item != null)
                    { 
                        // Delete file image of useful
                        Uploads.DeleteFile(string.Format("{0}{1}{2}", Settings.Default.SiteRootPath, Settings.Default.UsefulImageRootPath, item.ImagePath));
                        // Delete current useful
                        eDataConttext.Usefuls.DeleteOnSubmit(item);
                        eDataConttext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
                }
                catch (Exception exp)
                {
                    ViewData[Messages.MessageInfo] = exp.Message;
                    return View();
                }
        }
        #endregion

        #region GET: /Useful/Edit/5

        public ActionResult Edit(int id)
        {
                try
                {
                    var item = eDataConttext.Usefuls.Single(e => e.ID == id);

                    return View(
                        new UsefulEditViewmodel
                        { 
                         Useful = item,
                         ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.UsefulImagePreviewUrlPrefix
                        });
                }
                catch (Exception exp)
                {
                    ViewData[Messages.MessageInfo] = exp.Message;
                    return View();
                }
        }
        #endregion

        #region POST: /Useful/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, UsefulEditViewmodel fromdata)
        {
                try
                {
                    fromdata.Useful = eDataConttext.Usefuls.Single(e => e.ID == id);
                    fromdata.Useful.ModifiedBy = UserManager.GetUserId();
                    fromdata.Useful.ModifiedDate = DateTime.Now;
                    UpdateModel(fromdata);
                    //image upload
                    HttpPostedFileBase fileImage = Request.Files["UsefulImage"];
                    if (fileImage != null && fileImage.FileName.Length > 0)
                    {
                        //Delete old image
                        if (!string.IsNullOrEmpty(fromdata.Useful.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}{2}", Settings.Default.SiteRootPath, Settings.Default.UsefulImageRootPath, "" + fromdata.Useful.ID + "_" + fromdata.Useful.ImagePath)))
                            Uploads.DeleteFile(string.Format("{0}{1}{2}", Settings.Default.SiteRootPath, Settings.Default.UsefulImageRootPath, "" + fromdata.Useful.ID + "_" + fromdata.Useful.ImagePath));
                        
                        //DO upload new image
                        fromdata.Useful.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.UsefulImageRootPath), "" + fromdata.Useful.ID);
                    }
                    
                    eDataConttext.SubmitChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception exp)
                {
                    ViewData[Messages.MessageInfo] = exp.Message;
                    return View();
                }
        }
        #endregion

    }
}
